<?php
class System_UserGroupController extends Apps_Controller_Action {

	// Default user_group_id
	const DEFAULT_USER_GROUP_ID = 1;

	public function indexAction() {
		$this->_forward('list');
	}

	public function listAction() {
		$this->actResolve('act_delete',
						  'delete', 'user-group', 'system', array('id' => $this->_getParam('item_checker')),
						  true);

		$q = $this->_dbAdapter
				  ->select()
				  ->from('user_group');

		$grid = new Apps_Plugin_Grid('userGroup');
		$grid->setTableCaption('Danh sách nhóm người dùng')
			 ->setData($q)
			 ->setTableColumnFormat(array(
			 			array(
			 					'title'   	=> 'Title',
			 					'dataField' => 'title'
			 				),
			 			array(
			 					'title'   	=> 'Tên Nhóm',
			 					'dataField' => 'name'
			 				),
			 			array(
			 					'title'   	=> 'Ghi chú',
			 					'dataField' => 'description'
			 				),
			 			array(
			 					'title'   	=> 'Ngày tạo',
			 					'dataField' => 'description'
			 				),
					 	array('title'      =>  'Sửa',
					 		  'html'       =>  array('<a href="/system/user-group/edit?id=%s"><i class="icon-edit" title="Sửa" ></i></a>', array('id')),
					 		  'width'	   => '2%'
					 	),
					 	array(
					 			'title'     =>  'Xóa',
					 		  	'html'      =>  array('<a href="/system/user-group/delete?id=%s">
							 		  				 <i class="icon-remove must-confirm" title="Xóa"
							 		  				 data-must-confirm-msg="Xóa nhóm người dùng khỏi hệ thống" ></i></a>',
							 		  				 array('id')),
					 		  	'width'	   	=> '2%'
					 	)
			 		));
		$this->view->grid = $grid;
	}

	public function addAction() {
	    $rq   = $this->_request;
        if($rq->isPost()) {
	        $data['title']  	 = $rq->getParam('group-title');
	        $data['name']  		 = $rq->getParam('group-name');
			$data['description'] = $rq->getParam('description');
	        $roles 		 		 = $rq->getParam('roles');

	        $tbUserGroup = new M_DbTable_UserGroup();
	        $tbGroupAction = new M_DbTable_GroupAction();

	        //ADD User Group
	        $r = $tbUserGroup->safelyInsert($data);
	        //ADD Role
	        if($r) {
		        foreach ($roles as $value) {
			        switch ($value) {
			        	// Access Labour
			        	case 'labour':
			        		$actionsList = array('all',            'all-detail',            'working',
				        						 'working-detail', 'retire',                'retire-detail',
				        						 'continue-queue', 'continue-queue-detail', 'escaped',
				        						 'escaped-detail', 'missing',			    'missing-detail',
				        						 'died',		   'died-detail',		    'registered',
				        						 'registered-detail', 'index', 'end-turn', 'end-turn-detail');
			        		foreach ($actionsList as $value) {
			        			$actionId 			= $tbGroupAction->getAction('labour', 'list', $value);
			        			$d['user_group_id'] = $r;
								$d['acl_action_id'] = $actionId['id'];
			        			$tbGroupAction->safelyInsert($d);
			        		}

			        		$actionsReview = array('index', 'profile', 'paper',
			        							   'representative', 'experience');
			        		foreach ($actionsReview as $value) {
			        			$actionId 			= $tbGroupAction->getAction('labour', 'review', $value);
			        			$d['user_group_id'] = $r;
								$d['acl_action_id'] = $actionId['id'];
			        			$tbGroupAction->safelyInsert($d);
			        		}
				        	break;
				        // Manage Labour
			        	case 'labour-manage':
			        		$controllers = array('list', 'index', 'personal', 'review', 'register');
			        		foreach ($controllers as $value) {
			        			$actionIds = $tbGroupAction->getArrayAction('labour', $value);
			        			foreach ($actionIds as $k => $v) {
				        			$d['user_group_id'] = $r;
									$d['acl_action_id'] = $v['id'];
				        			$tbGroupAction->safelyInsert($d);
			        			}
			        		}
		        			break;

		        		// Access Work
			        	case 'work':
			        		$actionsList = array('allocated',      'allocated-detail',      'working',
				        						 'working-detail', 'retire',                'retire-detail',
				        						 'continue-queue', 'continue-queue-detail', 'escaped',
				        						 'escaped-detail', 'missing',			    'missing-detail',
				        						 'died',		   'died-detail',		    'deallocated',
				        						 'deallocated-detail', 'end-turn', 'end-turn-detail');
			        		foreach ($actionsList as $value) {
			        			$actionId 			= $tbGroupAction->getAction('labour', 'list', $value);
			        			$d['user_group_id'] = $r;
								$d['acl_action_id'] = $actionId['id'];
			        			$tbGroupAction->safelyInsert($d);
			        		}

			        		$actionsReview = array('index', 'profile', 'paper',
			        							   'representative', 'experience');
			        		foreach ($actionsReview as $value) {
			        			$actionId 			= $tbGroupAction->getAction('labour', 'review', $value);
			        			$d['user_group_id'] = $r;
								$d['acl_action_id'] 	= $actionId['id'];
			        			$tbGroupAction->safelyInsert($d);
			        		}

			        		$controllerListContract = array('contract-list', 'index');
			        		foreach ($controllerListContract as $value) {
			        			$actionIds = $tbGroupAction->getArrayAction('work', $value);
			        			foreach ($actionIds as $k => $v) {
			        				$d['user_group_id'] = $r;
			        				$d['acl_action_id'] = $v['id'];
			        				$tbGroupAction->safelyInsert($d);
			        			}
			        		}

				        	break;
				        //Manage Work / Contract
			        	case 'work-manage':
		        			$controllers = array('index', 'allocate', 'contract', 'contract-list', 'start-turn', 'end-turn', 'contract-liquidate');
			        		foreach ($controllers as $value) {
			        			$actionIds = $tbGroupAction->getArrayAction('work', $value);
			        			foreach ($actionIds as $k => $v) {
				        			$d['user_group_id'] = $r;
									$d['acl_action_id'] = $v['id'];
				        			$tbGroupAction->safelyInsert($d);
			        			}
			        		}
		        			break;
		        		//Access Salary
			        	case 'salary':
			        		$controllers = array('list');
			        		foreach ($controllers as $value) {
			        			$actionIds = $tbGroupAction->getArrayAction('salary', $value);
			        			foreach ($actionIds as $k => $v) {
				        			$d['user_group_id'] = $r;
									$d['acl_action_id'] = $v['id'];
				        			$tbGroupAction->safelyInsert($d);
			        			}
			        		}
			        		break;
			        	//Access Salary
			        	case 'salary-manage':
		        			$controllers = array('index', 		'ex-external', 'external',
		        								 'ex-internal', 'internal',    'list',
		        								 'preview', 	'template');
			        		foreach ($controllers as $value) {
			        			$actionIds = $tbGroupAction->getArrayAction('salary', $value);
			        			foreach ($actionIds as $k => $v) {
				        			$d['user_group_id'] = $r;
									$d['acl_action_id'] = $v['id'];
				        			$tbGroupAction->safelyInsert($d);
			        			}
			        		}
		        			break;
		        		//Access Insurance
			        	case 'insurance':
			        		$controllers = array('list');
			        		foreach ($controllers as $value) {
			        			$actionIds = $tbGroupAction->getArrayAction('insurance', $value);
			        			foreach ($actionIds as $k => $v) {
				        			$d['user_group_id'] = $r;
									$d['acl_action_id'] = $v['id'];
				        			$tbGroupAction->safelyInsert($d);
			        			}
			        		}
			        		break;
			        	//Manage Insurance
			        	case 'insurance-manage':
		        			$controllers = array('list', 'process', 'template');
			        		foreach ($controllers as $value) {
			        			$actionIds = $tbGroupAction->getArrayAction('insurance', $value);
			        			foreach ($actionIds as $k => $v) {
				        			$d['user_group_id'] = $r;
									$d['acl_action_id'] = $v['id'];
				        			$tbGroupAction->safelyInsert($d);
			        			}
			        		}
		        			break;
		        		//Access Management
			        	case 'management':
			        		$actionIds = $tbGroupAction->getActionIndexOrList('management');
		        			foreach ($actionIds as $value) {
			        			$d['user_group_id'] = $r;
								$d['acl_action_id'] = $value['id'];
			        			$tbGroupAction->safelyInsert($d);
		        			}
			        		break;
			        	//Manage Management
			        	case 'management-manage':
		        			$controllers = array('broker'				, 'contract-type',
		        								 'insurance'			,'insurance-company',
		        								 'insurance-duration'   , 'labour-degree-status',
		        								 'labour-marital-status', 'labour-passport-status',
		        								 'labour-photo-type'	, 'labour-visa-status',
		        								 'management-unit'		, 'ship',
		        								 'ship-type'			, 'ship-weight',
		        								 'ship-category');
			        		foreach ($controllers as $value) {
			        			$actionIds = $tbGroupAction->getArrayAction('management', $value);
			        			foreach ($actionIds as $k => $v) {
				        			$d['user_group_id'] = $r;
									$d['acl_action_id'] = $v['id'];
				        			$tbGroupAction->safelyInsert($d);
			        			}
			        		}
		        			break;
			        	//Manage System
			        	case 'system-manage':
		        			$controllers = array('index', 'auth',
		        								 'user',  'user-group');
			        		foreach ($controllers as $value) {
			        			$actionIds = $tbGroupAction->getArrayAction('system', $value);
			        			foreach ($actionIds as $k => $v) {
				        			$d['user_group_id'] = $r;
									$d['acl_action_id'] = $v['id'];
				        			$tbGroupAction->safelyInsert($d);
			        			}
			        		}
		        			break;
			        	default:
			        		break;
			        }
		        }
	        }
        	$this->goToIndexAction();
        }
	}


	public function editAction() {
		$rq            = $this->_request;
		$tbUserGroup   = new M_DbTable_UserGroup();
		$tbGroupAction = new M_DbTable_GroupAction();
		$tbUser 	   = new M_DbTable_User();

		// Create new Group and Delete old Group
		if($rq->isPost()) {
			$oldGroupId 		 = $rq->getParam('id');
			$data['title']  	 = $rq->getParam('group-title');
			$data['name']  		 = $rq->getParam('group-name');
			$data['description'] = $rq->getParam('description');
			$roles 		 		 = $rq->getParam('roles');

//ADD User Group
	        $r = $tbUserGroup->safelyInsert($data);
	        //ADD Role
	        if($r) {
		        foreach ($roles as $value) {
			        switch ($value) {
			        	// Access Labour
			        	case 'labour':
			        		$actionsList = array('all',            'all-detail',            'working',
				        						 'working-detail', 'retire',                'retire-detail',
				        						 'continue-queue', 'continue-queue-detail', 'escaped',
				        						 'escaped-detail', 'missing',			    'missing-detail',
				        						 'died',		   'died-detail',		    'registered',
				        						 'registered-detail', 'index', 'end-turn', 'end-turn-detail');
			        		foreach ($actionsList as $value) {
			        			$actionId 			= $tbGroupAction->getAction('labour', 'list', $value);
			        			$d['user_group_id'] = $r;
								$d['acl_action_id'] = $actionId['id'];
			        			$tbGroupAction->safelyInsert($d);
			        		}

			        		$actionsReview = array('index', 'profile', 'paper',
			        							   'representative', 'experience');
			        		foreach ($actionsReview as $value) {
			        			$actionId 			= $tbGroupAction->getAction('labour', 'review', $value);
			        			$d['user_group_id'] = $r;
								$d['acl_action_id'] = $actionId['id'];
			        			$tbGroupAction->safelyInsert($d);
			        		}
				        	break;
				        // Manage Labour
			        	case 'labour-manage':
			        		$controllers = array('list', 'index', 'personal', 'review', 'register');
			        		foreach ($controllers as $value) {
			        			$actionIds = $tbGroupAction->getArrayAction('labour', $value);
			        			foreach ($actionIds as $k => $v) {
				        			$d['user_group_id'] = $r;
									$d['acl_action_id'] = $v['id'];
				        			$tbGroupAction->safelyInsert($d);
			        			}
			        		}
		        			break;

		        		// Access Work
			        	case 'work':
			        		$actionsList = array('allocated',      'allocated-detail',      'working',
				        						 'working-detail', 'retire',                'retire-detail',
				        						 'continue-queue', 'continue-queue-detail', 'escaped',
				        						 'escaped-detail', 'missing',			    'missing-detail',
				        						 'died',		   'died-detail',		    'deallocated',
				        						 'deallocated-detail', 'end-turn', 'end-turn-detail');
			        		foreach ($actionsList as $value) {
			        			$actionId 			= $tbGroupAction->getAction('labour', 'list', $value);
			        			$d['user_group_id'] = $r;
								$d['acl_action_id'] = $actionId['id'];
			        			$tbGroupAction->safelyInsert($d);
			        		}

			        		$actionsReview = array('index', 'profile', 'paper',
			        							   'representative', 'experience');
			        		foreach ($actionsReview as $value) {
			        			$actionId 			= $tbGroupAction->getAction('labour', 'review', $value);
			        			$d['user_group_id'] = $r;
								$d['acl_action_id'] 	= $actionId['id'];
			        			$tbGroupAction->safelyInsert($d);
			        		}

			        		$controllerListContract = array('contract-list', 'index');
			        		foreach ($controllerListContract as $value) {
			        			$actionIds = $tbGroupAction->getArrayAction('work', $value);
			        			foreach ($actionIds as $k => $v) {
			        				$d['user_group_id'] = $r;
			        				$d['acl_action_id'] = $v['id'];
			        				$tbGroupAction->safelyInsert($d);
			        			}
			        		}

				        	break;
				        //Manage Work / Contract
			        	case 'work-manage':
		        			$controllers = array('index', 'allocate', 'contract', 'contract-list', 'start-turn', 'end-turn', 'contract-liquidate');
			        		foreach ($controllers as $value) {
			        			$actionIds = $tbGroupAction->getArrayAction('work', $value);
			        			foreach ($actionIds as $k => $v) {
				        			$d['user_group_id'] = $r;
									$d['acl_action_id'] = $v['id'];
				        			$tbGroupAction->safelyInsert($d);
			        			}
			        		}
		        			break;
		        		//Access Salary
			        	case 'salary':
			        		$controllers = array('list');
			        		foreach ($controllers as $value) {
			        			$actionIds = $tbGroupAction->getArrayAction('salary', $value);
			        			foreach ($actionIds as $k => $v) {
				        			$d['user_group_id'] = $r;
									$d['acl_action_id'] = $v['id'];
				        			$tbGroupAction->safelyInsert($d);
			        			}
			        		}
			        		break;
			        	//Access Salary
			        	case 'salary-manage':
		        			$controllers = array('index', 		'ex-external', 'external',
		        								 'ex-internal', 'internal',    'list',
		        								 'preview', 	'template');
			        		foreach ($controllers as $value) {
			        			$actionIds = $tbGroupAction->getArrayAction('salary', $value);
			        			foreach ($actionIds as $k => $v) {
				        			$d['user_group_id'] = $r;
									$d['acl_action_id'] = $v['id'];
				        			$tbGroupAction->safelyInsert($d);
			        			}
			        		}
		        			break;
		        		//Access Insurance
			        	case 'insurance':
			        		$controllers = array('list');
			        		foreach ($controllers as $value) {
			        			$actionIds = $tbGroupAction->getArrayAction('insurance', $value);
			        			foreach ($actionIds as $k => $v) {
				        			$d['user_group_id'] = $r;
									$d['acl_action_id'] = $v['id'];
				        			$tbGroupAction->safelyInsert($d);
			        			}
			        		}
			        		break;
			        	//Manage Insurance
			        	case 'insurance-manage':
		        			$controllers = array('list', 'process', 'template');
			        		foreach ($controllers as $value) {
			        			$actionIds = $tbGroupAction->getArrayAction('insurance', $value);
			        			foreach ($actionIds as $k => $v) {
				        			$d['user_group_id'] = $r;
									$d['acl_action_id'] = $v['id'];
				        			$tbGroupAction->safelyInsert($d);
			        			}
			        		}
		        			break;
		        		//Access Management
			        	case 'management':
			        		$actionIds = $tbGroupAction->getActionIndexOrList('management');
		        			foreach ($actionIds as $value) {
			        			$d['user_group_id'] = $r;
								$d['acl_action_id'] = $value['id'];
			        			$tbGroupAction->safelyInsert($d);
		        			}
			        		break;
			        	//Manage Management
			        	case 'management-manage':
		        			$controllers = array('broker'				, 'contract-type',
		        								 'insurance'			,'insurance-company',
		        								 'insurance-duration'   , 'labour-degree-status',
		        								 'labour-marital-status', 'labour-passport-status',
		        								 'labour-photo-type'	, 'labour-visa-status',
		        								 'management-unit'		, 'ship',
		        								 'ship-type'			, 'ship-weight',
		        								 'ship-category');
			        		foreach ($controllers as $value) {
			        			$actionIds = $tbGroupAction->getArrayAction('management', $value);
			        			foreach ($actionIds as $k => $v) {
				        			$d['user_group_id'] = $r;
									$d['acl_action_id'] = $v['id'];
				        			$tbGroupAction->safelyInsert($d);
			        			}
			        		}
		        			break;
			        	//Manage System
			        	case 'system-manage':
		        			$controllers = array('index', 'auth',
		        								 'user',  'user-group');
			        		foreach ($controllers as $value) {
			        			$actionIds = $tbGroupAction->getArrayAction('system', $value);
			        			foreach ($actionIds as $k => $v) {
				        			$d['user_group_id'] = $r;
									$d['acl_action_id'] = $v['id'];
				        			$tbGroupAction->safelyInsert($d);
			        			}
			        		}
		        			break;
			        	default:
			        		break;
					}
				}
				$tbUser->safelyUpdate(array('user_group_id' => $r), array('user_group_id = ?' => $oldGroupId));
				$tbUserGroup->delete(array('id = ?' => $oldGroupId));
			}
			$this->goToIndexAction();
		}

		// Get data show in Form
		$userGroupId   = $rq->getParam('id');
		if(!$userGroupId || !($dataGroup = $tbUserGroup->fetchRow(array('id=?' => $userGroupId))->toArray())) {
			$this->_flashMessenger->addMessage(self::$msgNoRecordFound);
			return $this->goToIndexAction();
		}


		// Group_Default cannot edit
			if($userGroupId == self::DEFAULT_USER_GROUP_ID) {
				$this->_flashMessenger->addMessage(self::$msgUpdateFailed);
				return $this->goToIndexAction();
			}

		// Get Roles  to show in checkbox
			$rolesGroup = array();

			$privilege = $tbGroupAction->getListActionFromGroupAction($userGroupId);
			foreach ($privilege as $value) {
				if($value['module_name'] == 'labour') {
					if($value['controller_name'] == 'list') {
						$rolesGroup[] = 'labour';
					}
				}
				if($value['module_name'] == 'labour') {
					if($value['controller_name'] == 'register') {
						$rolesGroup[] = 'labour-manage';
					}
				}
				if($value['module_name'] == 'work') {
					if($value['controller_name'] == 'contract-list') {
						$rolesGroup[] = 'work';
					}
				}
				if($value['module_name'] == 'work') {
					if($value['controller_name'] == 'allocate') {
						$rolesGroup[] = 'work-manage';
					}
				}
				if($value['module_name'] == 'salary') {
					if($value['controller_name'] == 'list') {
						$rolesGroup[] = 'salary';
					}
				}
				if($value['module_name'] == 'salary') {
					if($value['controller_name'] == 'external') {
						$rolesGroup[] = 'salary-manage';
					}
				}
				if($value['module_name'] == 'insurance') {
					if($value['controller_name'] == 'list') {
						$rolesGroup[] = 'insurance';
					}
				}
				if($value['module_name'] == 'insurance') {
					if($value['controller_name'] == 'process') {
						$rolesGroup[] = 'insurance-manage';
					}
				}
				if($value['module_name'] == 'system') {
					if($value['controller_name'] == 'user-group') {
						$rolesGroup[] = 'system';
					}
				}
			}

			$privilegeManagement = $tbGroupAction->getListActionManagement($userGroupId);
			foreach ($privilegeManagement as $value) {
				if($value['action_name'] == 'index') {
					$rolesGroup[] = 'management';
				}
				if($value['action_name'] == 'add') {
					$rolesGroup[] = 'management-manage';
				}
			}

		$this->view->data  = $dataGroup;
		$this->view->roles = $rolesGroup;
	}

	public function deleteAction() {
		$this->disableLayout(true, true);
		$rq = $this->_request;
		$groupIds = $rq->getParam('id');

		if(!$groupIds) {$this->goToIndexAction();}

		$tbUserGroup   = new M_DbTable_UserGroup();
		$tbGroupAction = new M_DbTable_GroupAction();
		if(is_array($groupIds)) {
			foreach ($groupIds as $groupId) {

				// Group_Default cannot delete
					if($groupId == self::DEFAULT_USER_GROUP_ID) {
						$this->_flashMessenger->addMessage(self::$msgDeleteError);
						return $this->goToIndexAction();
					}

				$tbGroupAction->delete(array('user_group_id = ?' => $groupId));
				$tbUserGroup->delete(array('id = ?' => $groupId));
			}
			$this->goToIndexAction();
		} elseif (is_numeric($groupIds)) {

			// Group_Default cannot delete
				if($groupIds == self::DEFAULT_USER_GROUP_ID) {
					$this->_flashMessenger->addMessage(self::$msgDeleteError);
					return $this->goToIndexAction();
				}

			$tbGroupAction->delete(array('user_group_id = ?' => $groupIds));
			$r = $tbUserGroup->delete(array('id = ?' => $groupIds));
			$this->_flashMessenger->addMessage($r ? self::$msgDeleteSuccess : self::$msgDeleteError);
			$this->goToIndexAction();
		} else {
			$this->goToIndexAction();
		}
	}
}
